import logging

import pylons.decorators

from cibynet.lib.base import *
from cibynet.lib.auth import authorisation

log = logging.getLogger(__name__)


class AuthController(BaseController):
  """Authentication related stuff.
  """

  def logout(self, environ):
    """Redirect the user to the previous page. 
    The un-authentication is done by a previous WSGI layer.
    """
    path_info = environ['PATH_INFO']
    if path_info.endswith(g.SIGNOUT_PART):
      h.redirect_to(path_info[:0-len(g.SIGNOUT_PART)])
    else:
      h.redirect_to("/")
      
  def login(self, environ, start_response):
    """Display a login form.
    """
    # Do not make abort(401) here: we deserve a "200 status"
    path_info = environ['PATH_INFO']
    return render("/login/form.mako", login_name='wsgilogin', 
              password_name='wsgipassword')
    
  def nothing(self, environ, start_response):
    """Does nothing!
    """
    pass
    
  @pylons.decorators.jsonify
  def ajax_login(self, environ, start_response):
    """Check about authentication and send back feedback.
    The real authentication part is done by  previous WSGI layer.
    This method also introduce a penalty system: 
      to many attempts to log in = prevented from login for some time.
    """
    answer = {}
    if authorisation.UserIsAuthenticated():
      answer['ok'] = True
      answer['penalty'] = 0
    else:
      penalty = environ.get("FAILED_AUTHENTICATION_PENALTY", 0)
      answer['ok'] = False
      answer['penalty'] = penalty
      msg_penalty = ""
      if penalty:
        msg_penalty = "Trials blocked for %i seconds." % penalty
      if environ.get("FAILED_AUTHENTICATION_TEMPORIZED"):
        msg = ('Your IP address has been prevented from '
               'authentication due to a high number of trials. '
               'Please try later.')
      else:
        msg = 'Login or password incorrect. %s' % msg_penalty
      answer['msg'] = msg
    return answer
